import Vue from 'vue'
import VueRouter from 'vue-router'

const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) { return originalReplace.call(this, location).catch(err => err); };

Vue.use(VueRouter)



const routes = [
  {
    path: "/",
    redirect: "/home"
  },
  {
    path: '/home',
    component: () => import("../views/home/Home.vue")
  },

  {
    path: '/category',
    component: () => import("../views/category/Category.vue")
  },

  {
    path: '/cart',
    component: () => import("../views/cart/Cart.vue")
  },

  {
    path: '/profile',
    component: () => import("../views/profile/Profile.vue")
  },
  {
    path: '/detail/:iid',
    component: () => import('../views/detail/Detail.vue')
  },
  {
    path: '/regisetr',
    component: () => import('../views/register/Register.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: "/",
      redirect: "/home"
    },
    {
      path: '/home',
      component: () => import("../views/home/Home.vue")
    },

    {
      path: '/category',
      component: () => import("../views/category/Category.vue")
    },

    {
      path: '/cart',
      component: () => import("../views/cart/Cart.vue")
    },

    {
      path: '/profile',
      component: () => import("../views/profile/Profile.vue")
    },
    {
      path: '/detail/:iid',
      component: () => import('../views/detail/Detail.vue')
    },
    {
      path: '/regisetr',
      component: () => import('../views/register/Register.vue')
    }
  ]
})



// // 路由导航守卫
router.beforeEach((to, form, next) => {
  console.log(to, form);
  // 如果sessionStorage中有token 就放行
  if (window.localStorage.getItem("token")) {
    next()
    // 如果没有
  } else {
    // 如果你去登录页面就放行
    if (to.path === "/regisetr") {
      next()
      // 如果你没有token 也不是去登录页面的话
      // 强行跳转登陆页面
    } else {
      next("/regisetr")
    }
  }

})

export default router
